<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Http\Requests\AdminGoodsRequest;
use App\Http\Requests\AdminGoodsEditRequest;
use App\Http\Requests\AdminGoodsSalesRequest;
use App\Http\Controllers\Controller;
use App\Model\Goods;
use App\Model\Goodsattr;
use App\Model\Goodssale;
use App\Model\Goodsspecs;
use App\Model\Goodstype;
use App\Model\Goodspic;
use App\Model\Goodsbrand;
use App\Model\AdminLoopModel;
use Illuminate\Database\QueryException;
use App\Http\Controllers\Api\CommonApi;
use App\Http\Controllers\Api\SearchApi;
use Illuminate\Support\Facades\Redis;
use DB;

class AdminGoodsListController extends Controller
{
	/**
	 * 显示商品列表页
	 */
    public function AdminGoodsList()
    {
    	//查询所有的商品
    	$goods = Goods::select('id', 'type_id', 'brand_id', 'goods_name', 'goods_pic', 'price', 'click_num', 'promate', 'status')->get();

    	//查询促销表
    	$sale = Goodssale::select('id', 'goods_id', 'start_time', 'end_time', 'status')->get()->toArray();

    	foreach ($sale as $v) {

    		//判断是否已经过了促销时间
    		if ($v['end_time'] < date('Y-m-d H:i:s')) {

    			//把商品表促销状态改为否
    			Goods::where('id', $v['goods_id'])->update(['promate' => 0]);

    			//删除促销信息
    			Goodssale::where('id', $v['id'])->delete();

    			//促销的集合和哈希的键
    			$setGoodsKey = 'goods_sale_set_data';
	    		$hashGoodsKey = 'goods_sale_hash_data:'.$v['goods_id'];

    			//删除Redis中的促销
	    		Redis::sRem($setGoodsKey, $hashGoodsKey);
			    Redis::del($hashGoodsKey);

			    //判断是否是热销商品
			    $good = Goods::find($v['goods_id']);
			    if ($good->buy_num < 100) {

			    	//商品属性的集合
				    $setColorKey = 'goods_set_color_data:'.$v['goods_id'];
				    $setSizeKey = 'goods_set_size_data:'.$v['goods_id'];

				    //删除其在Redis的商品属性
				    Redis::del($setColorKey);
				    Redis::del($setSizeKey);

				    //商品图片的集合
				    $setPicKey = 'goods_set_pic_data:'.$v['goods_id'];

				    //删除其在Redis的图片
				    Redis::del($setPicKey);
			    }

    		}
    	}

    	return view('Admin.goods.product-goodslist', ['goods' => $goods]);
    }


    /**
     * 显示商品添加页
     */
    public function AdminGoodsAdd()
    {
    	//查询商品分类表
    	$type = DB::select('select id,type_name,pid,path from shop_goods_types order by concat(path, id)');

    	//查询商品品牌表
    	$brand = DB::table('shop_goods_brands')->select('id', 'brand_name')->get();

    	return view('Admin.goods.product-goodsadd', ['type' => $type, 'brand' => $brand]);
    }


    /**
     * 处理添加商品
     */
    public function AdminAddGoods(AdminGoodsRequest $req)
    {

    	//要存到商品表的数据
    	$goods['goods_name'] = $req->input('good_name');
    	$goods['price'] = $req->input('price');
    	$goods['brand_id'] = $req->input('brand');
    	$goods['type_id'] = $req->input('type');
    	$goods['status'] = 0;
    	$goods['promate'] = $req->input('promate');
    	$goods['click_num'] = 0;
    	$goods['buy_num'] = 0;
    	$goods['created_at'] = date('Y-m-d H:i:s');
    	$goods['updated_at'] = date('Y-m-d H:i:s');


    	//处理文件上传
    	if (!empty($req->file('pic'))) {

	    	$files = new CommonApi();
	    	$res = $files->uploadToQiNiu($req, 'pic');

	    	if ($res['status'] == 4403) {
	    		return back()->with('msg', '没有文件上传');
	    	}
	    	if ($res['status'] == 4401) {
	    		return back()->with('msg', '上传文件不合法');
	    	}
	    	if ($res['status'] == 4044) {
	    		return back()->with('msg', '上传失败');
	    	}

	    	//接收上传图片后返回的路径
	    	$goods['goods_pic'] = $res['data']['key'];

    	} else {

    		return back()->with('msg', '文件不能为空');
    	}


    	//要存到商品属性表的数据
    	$attr['reserve'] = $req->input('reserve');
    	$attr['size'] = $req->input('size');
    	$attr['color'] = $req->input('color');
    	$attr['created_at'] = date('Y-m-d H:i:s');
    	$attr['updated_at'] = date('Y-m-d H:i:s');

    	//要存进商品规格表的数据
    	$specs['goods_desc'] = $req->input('good_desc');
    	$specs['goods_content'] = $req->input('content');
    	// dd($specs['goods_content']);
    	//转换详细内容为json数据
    	$specs['goods_content'] = json_encode($specs['goods_content']);
    	$specs['created_at'] = date('Y-m-d H:i:s');
    	$specs['updated_at'] = date('Y-m-d H:i:s');

    	//开启事务
    	DB::beginTransaction();
    	try{

	    	//存入数据库
	    	//存入商品表返回商品ID
	    	$id = Goods::insertGetId($goods);

	    	//存入属性表
	    	$attr['goods_id'] = $id;
	    	Goodsattr::insert($attr);


	    	//判断是否为促销商品
	    	if ($goods['promate'] == 1) {

		    	//要存到商品促销表的数据
		    	$promate['start_time'] = $req->input('start_time');
		    	//判断商品促销开始时间不能为空
		    	if (empty($promate['start_time'])) {
		    		return back()->with('msg', '请设置商品开始促销时间');
		    	}
		    	// dd($promate['start_time']);


		    	$promate['end_time'] = $req->input('end_time');
		    	//判断商品促销结束时间不能为空
		    	if (empty($promate['end_time'])) {
		    		return back()->with('msg', '请设置商品促销结束时间');
		    	}


		    	$promate['promate_price'] = $req->input('promate_price');
		    	//判断商品促销价格不能为空
		    	if (empty($promate['promate_price'])) {
		    		return back()->with('msg', '请设置商品促销价格');
		    	}


		    	$promate['promate_num'] = $req->input('promate_num');
		    	//判断商品促销数量不能为空
		    	if (empty($promate['promate_num'])) {
		    		return back()->with('msg', '请设置商品促销个数');
		    	}

		    	//判断商品促销个数不能大于库存
		    	if ($promate['promate_num'] > $attr['reserve']) {
		    		return back()->with('msg', '商品促销个数不能大于库存');
		    	}

		    	$promate['price'] = $goods['price'];
		    	$promate['goods_id'] = $id;
		    	$promate['goods_name'] = $goods['goods_name'];
		    	$promate['status'] = 0;
		    	$promate['created_at'] = date('Y-m-d H:i:s');
	    		$promate['updated_at'] = date('Y-m-d H:i:s');


		    	//存入商品促销表
		    	$saleId = Goodssale::insertGetId($promate);

	    	}

	    	//存入商品规格表
	    	$specs['goods_id'] = $id;
	    	Goodsspecs::insert($specs);

	    	//存入商品图片表
	    	$pics['goods_id'] = $id;
	    	$pics['pic'] = $goods['goods_pic'];
	    	$pics['created_at'] = date('Y-m-d H:i:s');
	    	$pics['updated_at'] = date('Y-m-d H:i:s');
	    	Goodspic::insert($pics);

	    	//提交事务
	    	DB::commit();

    	}catch(\Illuminate\Database\QueryException $e) {
    		//回滚事务
	    	DB::rollback();

	    	return back()->with('msg', '添加失败');
    	}

		//将促销商品写进Redis
    	if (!empty($saleId)) {

    		//关于商品促销的键
    		$setGoodsKey = 'goods_sale_set_data';
    		$hashGoodsKey = 'goods_sale_hash_data:'.$id;

    		//关于商品属性的键
    		$setColorKey = 'goods_set_color_data:'.$id;
    		$setSizeKey = 'goods_set_size_data:'.$id;

    		//添加到Redis
    		Redis::sAdd($setGoodsKey, $hashGoodsKey);
    		Redis::hMSet($hashGoodsKey, [
    			'id' => $saleId,
    			'goods_id' => $promate['goods_id'],
    			'goods_name' => $promate['goods_name'],
    			'goods_pic' => $goods['goods_pic'],
    			'start_time' => $promate['start_time'],
    			'end_time' => $promate['end_time'],
    			'price' => $promate['price'],
                'buy_num' => 0,
    			'promate_price' => $promate['promate_price'],
    			'promate_num' => $promate['promate_num']
    		]);

    		//把商品属性添加到Redis
    		Redis::sAdd($setColorKey, $attr['color']);
    		Redis::sAdd($setSizeKey, $attr['size']);


    		//关于商品图片的键
    		$setPicKey = 'goods_set_pic_data:'.$id;

    		//循环着把商品图片添加到Redis
    		Redis::sAdd($setPicKey, $pics['pic']);


    	}
        //查询品牌名
        $brand = Goodsbrand::find($goods['brand_id'])->toArray();

        //查询分类名
        $type = Goodstype::find($goods['type_id'])->toArray();

        //实例化讯搜类
        $search = new SearchApi('abc');

        $search->addDocumentData([
            'goods_id' => $id,
            'goods_name' => $goods['goods_name'],
            'price' => $goods['price'],
            'type_name' => $type['type_name'],
            'brand_name' => $brand['brand_name']

        ]);

        $Flush = $search->flush();



		return back()->with('msg', '添加成功');
    }


    /**
     * 显示添加商品属性页面
     */
    public function AdminGoodsAddAttr(Request $request)
    {
    	$id = $request->id;

    	//查询商品表
    	$good = Goods::select('id', 'goods_name')->where('id', $id)->first();

    	return view('Admin.goods.product-attradd', ['good' => $good]);
    }


    /**
     * 处理添加商品属性
     */
    public function AdminGoodsAttrAdd(Request $request)
    {
    	$this->validate($request, [
	        'color' => 'required',
	        'size' => 'required|numeric',
	        'reserve' => 'required|numeric'
    	], [
    		'color.required' => '请填写商品的颜色',
    		'size.required' => '请填写商品的尺寸',
    		'size.numeric' => '请填写合法的尺寸',
    		'reserve.required' => '请填写商品的库存',
    		'reserve.numeric' => '请填写合法的库存'
    	]);

    	$attr['goods_id'] = $request->input('goods_id');
    	$attr['color'] = $request->input('color');
    	$attr['size'] = $request->input('size');
    	//判断商品尺寸
    	if ($attr['size'] <= 0) {
    		return back()->with('msg', '商品的尺寸不合法');
    	}

    	$attr['reserve'] = $request->input('reserve');
    	//判断商品库存
    	if ($attr['reserve'] <= 0) {
    		return back()->with('msg', '商品的库存不合法');
    	}

    	$attr['created_at'] = date('Y-m-d H:i:s');
    	$attr['updated_at'] = date('Y-m-d H:i:s');

    	//添加到数据库
    	$id = Goodsattr::insertGetId($attr);

    	if (!$id) {
    		return back()->with('msg', '添加失败');
    	}

    	//查询是否是促销商品
    	$good = Goods::find($attr['goods_id']);

    	if ($good->promate == 1) {

    		//商品属性的集合
    		$setColorKey = 'goods_set_color_data:'.$good->id;
    		$setSizeKey = 'goods_set_size_data:'.$good->id;

    		Redis::sAdd($setColorKey, $attr['color']);
    		Redis::sAdd($setSizeKey, $attr['size']);

	    	return back()->with('msg', '添加成功');

    	}

    	//判断是否为热销商品
    	if ($good->buy_num > 100) {

    		//商品属性的集合
    		$setColorKey = 'goods_set_color_data:'.$good->id;
    		$setSizeKey = 'goods_set_size_data:'.$good->id;

    		Redis::sAdd($setColorKey, $attr['color']);
    		Redis::sAdd($setSizeKey, $attr['size']);
    	}

    	return back()->with('msg', '添加成功');

    }


    /**
     * 处理删除商品
     */
    public function AdminGoodsDelGoods(Request $request)
    {

    	$id = $request->id;

    	//查询商品的状态
    	$status = Goods::select('status')->where('id', $id)->first()->toArray();

    	if ($status['status'] == 0) {

    		return [
	    		'msg' => '该件商品在售中，不支持删除',
	    		'status' => 404,
    		];

    	}


    	//开启事务
    	DB::beginTransaction();
    	try{

    		//删除商品表数据
    		Goods::where('id', $id)->delete();

	    	//删除商品属性表数据
	    	Goodsattr::where('goods_id', $id)->delete();

	    	//删除商品图片表
	    	Goodspic::where('goods_id', $id)->delete();

	    	//删除商品规格表
	    	Goodsspecs::where('goods_id', $id)->delete();

	    	//删除商品对应的轮播图
	    	AdminLoopModel::where('goods_id', $id)->delete();

	    	//提交事务
	    	DB::commit();

	    }catch(\Illuminate\Database\QueryException $e) {
	    	//回滚事务
	    	DB::rollback();

	    	return [
	    		'msg' => '删除失败',
	    		'status' => 404,
    		];
	    }


    	return [
    		'msg' => '已删除',
    		'status' => 200,
    	];

    }


    /**
     * 显示编辑商品页面
     */
    public function AdminGoodsEdit(Request $request)
    {
    	$id = $request->id;

    	//查询商品信息
    	$res = Goods::find($id);

    	//查询品牌信息
    	$brands = Goodsbrand::select('id', 'brand_name')->get();
    	//查询分类信息
    	$types = DB::select('select id,type_name,pid,path from shop_goods_types order by concat(path, id)');
    	// dd($types);
    	//查询规格信息
    	$specs = Goodsspecs::select('goods_desc', 'goods_content')->where('goods_id', $res->id)->first();
    	// dd($specs);
    	$content = json_decode($specs->goods_content);

    	return view('Admin.goods.product-goodsedit', ['res' => $res, 'brands' => $brands, 'types' => $types, 'specs' => $specs, 'content' => $content]);
    }


    /**
     * 处理编辑商品
     */
    public function AdminEditGoods(AdminGoodsEditRequest $request)
    {
    	//修改商品表的数据
    	$id = $request->input('goods_id');
    	$goods['goods_name'] = $request->input('good_name');
    	$goods['price'] = $request->input('price');
    	$goods['brand_id'] = $request->input('brand');
    	$goods['type_id'] = $request->input('type');
    	$goods['updated_at'] = date('Y-m-d H:i:s');

    	//处理文件上传
    	if (!empty($request->file('pic'))) {

	    	$files = new CommonApi();
	    	$res = $files->uploadToQiNiu($request, 'pic');

	    	if ($res['status'] == 4403) {
	    		return back()->with('msg', '没有文件上传');
	    	}
	    	if ($res['status'] == 4401) {
	    		return back()->with('msg', '上传文件不合法');
	    	}
	    	if ($res['status'] == 4044) {
	    		return back()->with('msg', '上传失败');
	    	}

	    	//接收上传图片后返回的路径
	    	$goods['goods_pic'] = $res['data']['key'];

            //删除七牛云图片
            $files->deleteToQiNiu('shop_goods', 'goods_pic', $id);
    	}

    	//修改商品规格表的数据
    	$specs['goods_desc'] = $request->input('good_desc');
    	$specs['goods_content'] = json_encode($request->input('content'));
    	$specs['updated_at'] = date('Y-m-d H:i:s');

    	//开启事务
    	DB::beginTransaction();
    	try{
    		//判断用户是否修改了图片
    		if (!empty($goods['goods_pic'])) {

    			//查询出原来商品表中的图片
    			$pic = Goods::select('goods_pic')->where('id', $id)->first()->toArray();

    			//再去修改图片表对应的图片
    			Goodspic::where('pic', $pic)->update(['pic' => $goods['goods_pic']]);
    		}

    		//修改商品表中对应的数据
    		Goods::where('id', $id)->update($goods);

    		//修改规格表中对应的数据
    		Goodsspecs::where('goods_id', $id)->update($specs);

    		//提交事务
	    	DB::commit();
    	}catch(\Illuminate\Database\QueryException $e) {
	    	//回滚事务
	    	DB::rollback();

	    	return back()->with('msg', '修改失败');
	    }

	    //判断是否是热销商品
	    $good = Goods::find($id);
	    if ($good->buy_num > 100) {

	    	//删除Redis的热卖商品
	    	$hotGoodsSet = 'hot_goods_set';
	    	$hotGoodsHash = 'hot_goods_hash_id:'.$id;

	    	//判断热销的哈希是否不为空
		    if( !empty(Redis::hGetAll($hotGoodsHash))) {

		    	Redis::del($hotGoodsHash);
		    	Redis::sRem($hotGoodsSet, $hotGoodsHash);
		    }

		    //把商品图片存到Redis
		    //查询出该商品的所有图片
		    $goodspic = Goodspic::select('pic')->where('goods_id', $id)->get()->toArray();
		    $setPicKey = 'goods_set_pic_data:'.$id;

		    foreach ($goodspic as $p) {
		    	Redis::sAdd($setPicKey, $p['pic']);
		    }

		    //在把新的存到Redis
		    Redis::sAdd($hotGoodsSet, $hotGoodsHash);
		    Redis::hMSet($hotGoodsHash, [
		    	'id' => $id,
		    	'goods_name' => $good->goods_name,
		    	'price' => $good->price,
		    	'goods_pic' => $good->goods_pic
		    ]);



            //修改商品分类是顺便对redis里的分类下的商品做出修改
            $setOldTypeKey = 'types_with_goods_set_data:'.$request->oldType_id;
            $setNewTypeKey = 'types_with_goods_set_data:'.$request->input('type');
            $hashKey = 'types_with_goods_hash_data:'.$id;

            Redis::sRem($setOldTypeKey, $hashKey);

            Redis::del($hashKey);

            Redis::sAdd($setNewTypeKey, $hashKey);

            Redis::hMSet($hashKey, ['id' => $request->id,
                                    'goods_name' => $request->input('good_name'),
                                    'goods_pic' => $good->goods_pic,
                                    'price'     => $good->price
                                    ]);


	    }

        //查询品牌名
        $brand = Goodsbrand::find($goods['brand_id'])->toArray();

        //查询分类名
        $type = Goodstype::find($goods['type_id'])->toArray();

        //实例化讯搜类
        $search = new SearchApi('abc');
        $search->updateDocumentData([
            'goods_id' => $id,
            'goods_name' => $goods['goods_name'],
            'price' => $goods['price'],
            'type_name' => $type['type_name'],
            'brand_name' => $brand['brand_name']
        ]);

        $Flush = $search->flush();

	    return back()->with('msg', '修改成功');
    }


    /**
     * 处理下架商品
     */
    public function AdminGoodsStop(Request $req)
    {
    	$id = $req->id;

    	$good = Goods::find($id);

    	//判断是否是促销中的商品
    	if ($good->promate == 1) {
    		return [
	    		'msg' => '该商品在促销中，不允许下架',
	    		'status' => 404,
    		];
    	}

    	//把商品的状态改为下架
    	$result = Goods::where('id', $id)->update(['status' => 2]);

    	if (!$result) {
    		return [
	    		'msg' => '下架失败',
	    		'status' => 404,
    		];
    	}


    	//删除Redis的热卖商品
    	$hotGoodsSet = 'hot_goods_set';
    	$hotGoodsHash = 'hot_goods_hash_id:'.$id;

	    if( !empty(Redis::hGetAll($hotGoodsHash))) {

	    	Redis::del($hotGoodsHash);

	    	Redis::sRem($hotGoodsSet, $hotGoodsHash);
	    }

	    //Redis的商品属性集合
	    $setColorKey = 'goods_set_color_data:'.$id;
	    $setSizeKey = 'goods_set_size_data:'.$id;

	    //删除颜色集合
	    if (!empty(Redis::sMembers($setColorKey))) {
	    	Redis::del($setColorKey);
	    }

	    //删除尺寸集合
	    if (!empty(Redis::sMembers($setSizeKey))) {
	    	Redis::del($setSizeKey);
	    }

	    //删除Redis的图片
	    $setPicKey = 'goods_set_pic_data:'.$id;
	    if (!empty(Redis::sMembers($setPicKey))) {
	    	Redis::del($setPicKey);
	    }

        //下架商时对首页商品的redis的同步
        $setTypeKey = 'types_with_goods_set_data:'.$good->type_id;
        $hashKey = 'types_with_goods_hash_data:'.$id;

        Redis::sRem($setTypeKey, $hashKey);

        Redis::del($hashKey);

        //实例化讯搜类
        $search = new SearchApi('abc');

        $search->deleteDocumentData($id);

    	return [
    		'msg' => '下架成功',
    		'status' => 200,
    	];

    }


    /**
     * 处理上架商品
     */
    public function AdminGoodsStart(Request $req)
    {
    	$id = $req->id;

    	//把商品的状态改为在售中
    	$good = Goods::where('id', $id)->update(['status' => 0]);

    	if (!$good) {
    		return [
	    		'msg' => '上架失败',
	    		'status' => 404,
    		];
    	}

    	//根据ID查询一条商品数据
	    $good = Goods::find($id);

    	//判断是否是热销商品
	    if ($good->buy_num > 100) {

	    	//热销商品的集合和哈希
	    	$hotGoodsSet = 'hot_goods_set';
	    	$hotGoodsHash = 'hot_goods_hash_id:'.$id;
              //修改商品分类是顺便对redis里的分类下的商品做出修改
            $setTypeKey = 'types_with_goods_set_data:'.$good->type_id;
            $hashKey = 'types_with_goods_hash_data:'.$id;

            Redis::sAdd($setTypeKey, $hashKey);

            Redis::hMSet($hashKey, ['id' => $good->id,
                                    'goods_name' => $good->goods_name,
                                    'goods_pic' => $good->goods_pic,
                                    'price'     => $good->price
                                    ]);

		    //再把新的存到Redis
		    Redis::sAdd($hotGoodsSet, $hotGoodsHash);
		    Redis::hMSet($hotGoodsHash, [
		    	'id' => $id,
		    	'goods_name' => $good->goods_name,
		    	'price' => $good->price,
		    	'goods_pic' => $good->goods_pic
		    ]);

		    //把商品的相关属性添加到Redis
		    $setColorKey = 'goods_set_color_data:'.$id;
		    $setSizeKey = 'goods_set_size_data:'.$id;


			//查询该商品的所有颜色
			$color = Goodsattr::select('color')->where('goods_id', $id)->groupBy('color')->get()->toArray();

			//查询该商品的所有尺寸
			$size = Goodsattr::select('size')->where('goods_id', $id)->groupBy('size')->get()->toArray();

			//将商品属性颜色添加进Redis
			foreach ($color as $v) {
				Redis::sAdd($setColorKey, $v['color']);
			}

			//将商品属性尺寸添加进Redis
			foreach ($size as $m) {
				Redis::sAdd($setSizeKey, $m['size']);
			}

		    //把商品图片存到Redis
		    //查询出该商品的所有图片
		    $goodspic = Goodspic::select('pic')->where('goods_id', $id)->get()->toArray();
		    $setPicKey = 'goods_set_pic_data:'.$id;

		    foreach ($goodspic as $p) {
		    	Redis::sAdd($setPicKey, $p['pic']);
		    }
	    }


        //查询品牌名
        $brand = Goodsbrand::find($good->brand_id)->toArray();

        //查询分类名
        $type = Goodstype::find($good->type_id)->toArray();

        //实例化讯搜类
        $search = new SearchApi('abc');

        $search->addDocumentData([
            'goods_id' => $id,
            'goods_name' => $good->goods_name,
            'price' => $good->price,
            'type_name' => $type['type_name'],
            'brand_name' => $brand['brand_name']

        ]);

    	return [
    		'msg' => '上架成功',
    		'status' => 200,
    	];

    }


    /**
     * 显示添加商品图片页面
     */
    public function AdminGoodsPic(Request $req)
    {
    	$id = $req->id;

    	$good = Goods::find($id);

    	return view('Admin.goods.product-goodspic', ['good' => $good]);
    }


    /**
     * 处理添加图片
     */
    public function AdminGoodsAddPic(Request $req)
    {
    	$good['goods_id'] = $req->input('goods_id');
    	$good['created_at'] = date('Y-m-d H:i:s');
    	$good['updated_at'] = date('Y-m-d H:i:s');

    	//处理文件上传
    	if (!empty($req->file('pic'))) {

	    	$files = new CommonApi();
	    	$res = $files->uploadToQiNiu($req, 'pic');

	    	if ($res['status'] == 4403) {
	    		return back()->with('msg', '没有文件上传');
	    	}
	    	if ($res['status'] == 4401) {
	    		return back()->with('msg', '上传文件不合法');
	    	}
	    	if ($res['status'] == 4044) {
	    		return back()->with('msg', '上传失败');
	    	}

	    	//接收上传图片后返回的路径
	    	$good['pic'] = $res['data']['key'];

    	} else {

    		return back()->with('msg', '文件不能为空');
    	}

    	if (!empty($good['pic'])) {

    		$id = Goodspic::insertGetId($good);

    		if (!$id) {

    			return back()->with('msg', '添加失败');
    		}

    		//根据商品ID查询一条商品数据
    		$result = Goods::find($good['goods_id']);

    		//商品图片的集合
    		$setPicKey = 'goods_set_pic_data:'.$good['goods_id'];

    		//判断是否是热销商品
    		if ($result->buy_num > 100) {

    			//添加到Redis
    			Redis::sAdd($setPicKey, $good['pic']);

    			return back()->with('msg', '添加成功');

    		}

    		//判断是否是促销商品
    		if ($result->promate == 1) {

    			//添加到Redis
    			Redis::sAdd($setPicKey, $good['pic']);
    		}

    		return back()->with('msg', '添加成功');
    	}

    	return back()->with('msg', '添加失败');

    }



    /**
     * 显示商品详情页
     */
    public function AdminGoodsDetail(Request $req)
    {
    	$id = $req->id;

    	$good = Goods::find($id);

    	//查询促销信息
    	$res = $good->sales;
    	// dd($res);

    	//查询品牌
    	$brand = $good->brands;

    	//查询分类
    	$type = $good->types;

    	//查询属性
    	$attrs = $good->attrs;

    	return view('Admin.goods.product-goodsdetail', ['good' => $good, 'res' => $res, 'brand' => $brand, 'type' => $type, 'attrs' => $attrs]);
    }



    /**
     * 显示编辑商品属性页面
     */
    public function AdminDetailEdit(Request $req)
    {
    	$id = $req->id;

    	$res = Goodsattr::where('id', $id)->first();

    	return view('Admin.goods.product-detailedit', ['res' => $res]);
    }


    /**
     * 处理编辑商品属性
     */
    public function AdminEditDetail(Request $request)
    {

    	$this->validate($request, [
	        'color' => 'required',
	        'size' => 'required|numeric',
	        'reserve' => 'required|numeric'
    	], [
    		'color.required' => '请填写商品的颜色',
    		'size.required' => '请填写商品的尺寸',
    		'size.numeric' => '请填写合法的尺寸',
    		'reserve.required' => '请填写商品的库存',
    		'reserve.numeric' => '请填写合法的库存'
    	]);

    	$id = $request->input('id');

    	$attrs['color'] = $request->input('color');
		$attrs['size'] = $request->input('size');
		$attrs['reserve'] = $request->input('reserve');
		$attrs['updated_at'] = date('Y-m-d H:i:s');

		$bol = Goodsattr::where('id', $id)->update($attrs);

		if (!$bol) {
			return back()->with('msg', '修改失败');
		}

		//查询是否是促销商品
		$attr = Goodsattr::find($id);
    	$good = $attr->goods;

    	if ($good->promate == 1) {

    		//商品属性的集合
    		$setColorKey = 'goods_set_color_data:'.$good->id;
    		$setSizeKey = 'goods_set_size_data:'.$good->id;

    		//删除Redis的属性集合
    		Redis::del($setColorKey);
    		Redis::del($setSizeKey);

    		//查询该商品的所有颜色
    		$color = Goodsattr::select('color')->where('goods_id', $good->id)->groupBy('color')->get()->toArray();

    		//查询该商品的所有尺寸
    		$size = Goodsattr::select('size')->where('goods_id', $good->id)->groupBy('size')->get()->toArray();

    		//添加颜色到集合
    		foreach ($color as $v) {
    			Redis::sAdd($setColorKey, $v['color']);
    		}

    		//添加尺寸到集合
    		foreach ($size as $m) {
    			Redis::sAdd($setSizeKey, $m['size']);
    		}

			return back()->with('msg', '修改成功');

    	}

    	//判断是否是热销商品
    	if ($good->buy_num > 100 ) {

    		//商品属性的集合
    		$setColorKey = 'goods_set_color_data:'.$good->id;
    		$setSizeKey = 'goods_set_size_data:'.$good->id;

    		//删除Redis属性的集合
    		Redis::del($setColorKey);
    		Redis::del($setSizeKey);

    		//查询该商品的所有颜色
    		$color = Goodsattr::select('color')->where('goods_id', $good->id)->groupBy('color')->get()->toArray();

    		//查询该商品的所有尺寸
    		$size = Goodsattr::select('size')->where('goods_id', $good->id)->groupBy('size')->get()->toArray();

    		//添加颜色到集合
    		foreach ($color as $v) {
    			Redis::sAdd($setColorKey, $v['color']);
    		}

    		//添加尺寸到集合
    		foreach ($size as $m) {
    			Redis::sAdd($setSizeKey, $m['size']);
    		}
    	}

		return back()->with('msg', '修改成功');
    }



    /**
     * 处理删除商品属性
     */
    public function AdminDetailDel(Request $req)
    {
    	$id = $req->id;

    	//根据ID查询一条商品属性数据
    	$attr = Goodsattr::find($id);
    	$good = $attr->goods;

    	//判断是否在促销
    	if ($good->promate == 1) {

    		return [
	    		'msg' => '删除失败,该商品在促销中,不允许删除其商品属性',
	    		'status' => 404,
    		];
    	}

    	//删除商品属性表的一条数据
    	$res = Goodsattr::where('id', $id)->delete();


    	if(!$res) {

    		return [
	    		'msg' => '删除失败',
	    		'status' => 404,
    		];
    	}

    	//判断是否是热销商品
    	if ($good->buy_num > 100) {

    		//商品属性的集合
    		$setColorKey = 'goods_set_color_data:'.$good->id;
    		$setSizeKey = 'goods_set_size_data:'.$good->id;

    		//删除商品属性集合
    		Redis::del($setColorKey);
    		Redis::del($setSizeKey);

    		//查询该商品的所有颜色
    		$color = Goodsattr::select('color')->where('goods_id', $good->id)->groupBy('color')->get()->toArray();

    		//查询该商品的所有尺寸
    		$size = Goodsattr::select('size')->where('goods_id', $good->id)->groupBy('size')->get()->toArray();

    		//添加颜色到集合
    		foreach ($color as $v) {
    			Redis::sAdd($setColorKey, $v['color']);
    		}

    		//添加尺寸到集合
    		foreach ($size as $m) {
    			Redis::sAdd($setSizeKey, $m['size']);
    		}
    	}

    	return [
	    		'msg' => '已删除',
	    		'status' => 200,
  		];
    }


    /**
     * 显示设置促销页面
     */
    public function AdminGoodsSales(Request $req)
    {
    	$id = $req->id;
    	$good = Goods::find($id);
    	return view('Admin.goods.product-goodssales', ['good' => $good]);
    }



    /**
     * 处理设置促销
     */
    public function AdminDoGoodsSales(AdminGoodsSalesRequest $req)
    {

    	$gid = $req->input('goods_id');
    	$good = Goods::find($gid);

    	$sales['goods_id'] = $gid;
    	$sales['goods_name'] = $good->goods_name;
    	$sales['price'] = $good->price;
    	$sales['start_time'] = $req->input('start_time');

    	$sales['end_time'] = $req->input('end_time');
    	$sales['promate_price'] = $req->input('promate_price');

    	//判断促销价不能小于0不能大于原价
    	if ($sales['promate_price'] <= 0 || $sales['promate_price'] > $sales['price']) {
    		return back()->with('msg', '促销价格不合法');
    	}

    	//查出商品的所有库存
    	$res = Goodsattr::select('reserve')->where('goods_id', $gid)->get();

    	//获取该商品的总库存
    	$reser = 0;
    	foreach ($res as $v) {
    		$reser += $v->reserve;
    	}

    	$sales['promate_num'] = $req->input('promate_num');

    	//判断促销数量不能小于等于0
    	if ($sales['promate_num'] < 0) {
    		return back()->with('msg', '促销数量不合法');
    	}

    	//判断促销数量不能大于库存
    	if ($sales['promate_num'] > $reser) {
    		return back()->with('msg', '促销数量不能大于库存');
    	}

    	$sales['status'] = 0;
    	$sales['created_at'] = date('Y-m-d H:i:s');
    	$sales['updated_at'] = date('Y-m-d H:i:s');

    	$id = Goodssale::insertGetId($sales);

    	if (!$id) {
    		return back()->with('msg', '设置失败');
    	}

        //查出该商品的总销量
        $good = Goods::find($gid);
        $buy_num = $good->buy_num;

    	//将促销存入Redis
		$setGoodsKey = 'goods_sale_set_data';
		$hashGoodsKey = 'goods_sale_hash_data:'.$gid;
		Redis::sAdd($setGoodsKey, $hashGoodsKey);
		Redis::hMSet($hashGoodsKey, [
			'id' => $id,
			'goods_id' => $sales['goods_id'],
			'goods_name' => $sales['goods_name'],
			'goods_pic' => $good->goods_pic,
			'start_time' => $sales['start_time'],
			'end_time' => $sales['end_time'],
			'price' => $sales['price'],
      'buy_num' => $buy_num,
			'promate_price' => $sales['promate_price'],
			'promate_num' => $sales['promate_num']
		]);

		//判断是否是热销商品
		if ($good->buy_num < 100) {

			//将商品属性添加进Redis
			$setColorKey = 'goods_set_color_data:'.$gid;
			$setSizeKey = 'goods_set_size_data:'.$gid;

			//查询该商品的所有颜色
			$color = Goodsattr::select('color')->where('goods_id', $gid)->groupBy('color')->get()->toArray();

			//查询该商品的所有尺寸
			$size = Goodsattr::select('size')->where('goods_id', $gid)->groupBy('size')->get()->toArray();

			//遍历把尺寸加入Redis
			foreach ($color as $v) {
				Redis::sAdd($setColorKey, $v['color']);
			}

			//遍历把颜色加入Redis
			foreach ($size as $m) {
				Redis::sAdd($setSizeKey, $m['size']);
			}

			//把商品图片存到Redis
		    //查询出该商品的所有图片
		    $goodspic = Goodspic::select('pic')->where('goods_id', $gid)->get()->toArray();
		    $setPicKey = 'goods_set_pic_data:'.$gid;

		    foreach ($goodspic as $p) {
		    	Redis::sAdd($setPicKey, $p['pic']);
		    }
		}

    	//修改商品的促销状态
    	Goods::where('id', $gid)->update(['promate' => 1]);

    	return back()->with('msg', '设置促销成功');
    }


    /**
     * 取消促销
     */
    public function AdminDelSales(Request $req)
    {
    	$gid = $req->id;

    	$id = Goodssale::where('goods_id', $gid)->delete();

    	if (!$id) {
    		return [
	    		'msg' => '取消失败',
	    		'status' => 404,
    		];
    	}

    	Goods::where('id', $gid)->update(['promate' => 0]);

    	//将Redis中的促销商品删除
	    $setGoodsKey = 'goods_sale_set_data';
	    $hashGoodsKey = 'goods_sale_hash_data:'.$gid;

	    Redis::sRem($setGoodsKey, $hashGoodsKey);
	    Redis::del($hashGoodsKey);

	    //查询商品是否为热销
	    $good = Goods::find($gid);
	    if ($good->buy_num < 100) {

		    //删除其在Redis的商品属性
		    $setColorKey = 'goods_set_color_data:'.$gid;
		    $setSizeKey = 'goods_set_size_data:'.$gid;

		    Redis::del($setColorKey);
		    Redis::del($setSizeKey);

		    //删除其在Redis的图片
		    $setPicKey = 'goods_set_pic_data:'.$gid;

		    Redis::del($setPicKey);
	    }


    	return [
	    		'msg' => '取消成功',
	    		'status' => 200,
    	];


    }



    /**
     * 显示图片列表
     */
    public function AdminGoodsImage(Request $req)
    {
    	$id = $req->id;
    	$good = Goods::find($id);
    	$res = Goodspic::select('id', 'goods_id', 'pic')->where('goods_id', $id)->get();
    	return view('Admin.goods.product-goodsimage', ['good' => $good, 'res' => $res]);
    }



    /**
     * 删除商品图片
     */
    public function AdminDelImage(Request $req)
    {
    	$id = $req->id;

    	//查询商品图片表
    	$res = Goodspic::find($id);

    	//查询商品表
    	$good = Goods::find($res->goods_id);

    	//判断是否是促销商品
    	if ($good->promate == 1) {
    		return [
	    		'msg' => '该商品在促销中，不允许删除其图片',
	    		'status' => 404,
    		];
    	}

    	//判断是否是删除图片表中的主图
    	if ($res->pic == $good->goods_pic) {
    		return [
	    		'msg' => '不允许删除商品主图',
	    		'status' => 404,
    		];
    	}

    	//删除图片
    	$id = Goodspic::where('id', $id)->delete();

    	if (!$id) {
    		return [
	    		'msg' => '删除失败',
	    		'status' => 404,
    		];
    	}

        // //删除七牛云图片
        // $files = new CommonApi();
        // $files->deleteToQiNiu('shop_goods_pics', 'pic', $id);

        //判断是否是热销商品
       	if ($good->buy_num > 100) {
       		//更新Redis的图片
	       	$setPicKey = 'goods_set_pic_data:'.$good->id;

			Redis::del($setPicKey);

			//查询出属于该商品的所有图片
			$pics = Goodspic::select('pic')->where('goods_id', $good->id)->get()->toArray();

			//遍历存入Redis
			foreach ($pics as $v) {
				Redis::sAdd($setPicKey, $v['pic']);
			}
       	}

    	return [
	    		'msg' => '删除成功',
	    		'status' => 200,
    	];
    }

}
